//
//  PMJobOrderDetailViewController.m
//  ERP
//
//  Created by goldeney on 15/1/12.
//  Copyright (c) 2015年 ShangHai Goldeneye Techonology Co.,Ltd. All rights reserved.
//

#import "PMJobOrderDetailViewController.h"
#import "PMJobOrderDetailViewCell.h"
#import "WebServiceCommonRequest.h"

#import "AutoTextTableViewCell.h"
#import "NSDictionary+DataFormat.h"
#import "PMRollingPlanDetailViewCell.h"

#import "GEObjectValueTableViewCell.h"
#import "Charts-Swift.h"
#import "PNChart.h"

#import "PMShipOrderDetailViewController.h"

@interface PMJobOrderDetailViewController ()

@property (nonatomic,strong) NSDictionary *contractBaseInfo;
@property (nonatomic,strong) NSMutableArray *contractData;

@property (nonatomic,strong) NSArray *orderData;
@property (nonatomic,assign) NSInteger orderContentState;//0加载中，1未找到数据，2加载失败，3加载成功

@end

@implementation PMJobOrderDetailViewController
@synthesize tableView = _tableView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setTitle: @"任务单明细"];
    }
    return self;
}


- (void)getPassingParameter:(id)object
{
    NSDictionary *dic = object;
    self.contractBaseInfo = dic;
    NSMutableArray *contract = [NSMutableArray array];
    
    [self addContractInfoKey:@"工程名称" toKey:@"工程名称：" defaults:@"未知" format:nil form:dic toArray:contract];
    [self addContractInfoKey:@"施工单位" toKey:@"施工单位：" defaults:@"未知" format:nil form:dic toArray:contract];
    [self addContractInfoKey:@"施工部位" toKey:@"施工部位：" defaults:@"未知" format:nil form:dic toArray:contract];
    [self addContractInfoKey:@"工地地址" toKey:@"工地地址：" defaults:@"未知" format:nil form:dic toArray:contract];
    [self addContractInfoKey:@"砼强度" toKey:@"强度等级：" defaults:@"未知" format:nil form:dic toArray:contract];
    [self addContractInfoKey:@"浇筑方式" toKey:@"浇筑方式：" defaults:@"未知" format:nil form:dic toArray:contract];
    [self addContractInfoKey:@"计划方量" toKey:@"计划方量：" defaults:@"未知" format:@"%@方" form:dic toArray:contract];
    [self addContractInfoKey:@"累计发货方量" toKey:@"发货方量：" defaults:@"未知" format:@"%@方" form:dic toArray:contract];
    [self addContractInfoKey:@"工地联系人" toKey:@"联  系  人：" defaults:@"未知" format:nil form:dic toArray:contract];
    [self addContractInfoKey:@"工地联系电话" toKey:@"联系电话：" defaults:@"未知" format:nil form:dic toArray:contract];
    [self addContractInfoKey:@"工地计划开盘时间" toKey:@"计划开盘时间：" defaults:@"未知" format:nil form:dic toArray:contract];
    [self addContractInfoKey:@"实际开盘时间" toKey:@"实际开盘时间：" defaults:@"未知" format:nil form:dic toArray:contract];
    
    self.contractData = contract;
}

- (void)addContractInfoKey:(id)key toKey:(id)tokey defaults:(id)def format:(id)formatText
                      form:(NSDictionary*)dic toArray:(NSMutableArray*)array
{
    id value = [dic objectFormatForKey:key];
    if (!def) def = @"";
    
    if (!value){
        value = def;
    } else if (formatText) {
        value = [NSString stringWithFormat:formatText,value];
    }
    
    NSDictionary *valueDic = [NSDictionary dictionaryWithObject:value forKey:tokey];
    [array addObject:valueDic];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tableView registerClass:[PMJobOrderDetailViewCell class] forCellReuseIdentifier:@"PMJobOrderDetailViewCell"];
    
    //获取任务单所有车辆
    [self getJobOrderInfo];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 网络获取车辆信息
- (void)getJobOrderInfo
{
    //判断是否需要获取订单
    if(!self.contractBaseInfo) return;
    
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeERP];
    [content setModuleType:@"SCDD_JRKB_RWDCL"];
    [content setStationID:self.stationID];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    NSString *jobOrder = [self.contractBaseInfo objectFormatStringForKey:@"任务单编号"];
    [content addParameterKey:@"任务单编号" value:jobOrder];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        if(firstArray && firstArray.count>0){
            self.orderData = firstArray;
            self.orderContentState = 3;
        } else {
            self.orderContentState = 1;
        }
        [self.tableView reloadData];
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.orderContentState = 2;
        [self.tableView reloadData];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.orderContentState = 2;
        [self.tableView reloadData];
    }];
}

#pragma mark
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if(self.contractData && self.contractData.count>0) return 3;
    else return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    } else if(section == 1){
        return 3;
        
    } else if(section == 2){
        if(self.orderContentState == 0) return 1;
        else if(self.orderContentState == 1) return 1;
        else if(self.orderContentState == 2) return 1;
        else if(self.orderContentState == 3) return self.orderData.count;
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0){
        AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"AutoTextTableViewCell"];
        [cell setDataArray:self.contractData];
        return cell;
        
    } else if(indexPath.section == 1){
        if (indexPath.row == 0) {
            NSString *identifier = [NSString stringWithFormat:@"GEObjectValueTableViewCell%ld",(long)indexPath.section];
            GEObjectValueTableViewCell *cell = [self.tableView getCellViewKey:identifier];
            if (cell == nil) {
                cell = [[GEObjectValueTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
                [self.tableView setCellView:cell key:identifier];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.userInteractionEnabled = NO;
                //添加图表
                [self todaysTaskingDrawCell:cell indexPath:indexPath];
            }
            return cell;
        }
        
        static NSString *CellIdentifier = @"PMRollingPlanDetailViewCell";
        PMRollingPlanDetailViewCell *cell = [[PMRollingPlanDetailViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleDefault;
        
        //添加分割线
        if(indexPath.row == 1){
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0.5, SuperWidth, 0.5)];
            lineView.backgroundColor = [UIColor colorWithWhite:0.65 alpha:0.3];
            [cell.contentView addSubview:lineView];
        } else {
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(48, 0.5, SuperWidth - 48, 0.5)];
            lineView.backgroundColor = [UIColor colorWithWhite:0.65 alpha:0.3];
            [cell.contentView addSubview:lineView];
        }
        
        //@类型(1:退回已签, 2:退回未签, 3:本日发货单, 4:所有发货单)
        if(indexPath.row == 1) {
            cell.btLabel.text = @"退回已签";
            cell.fbtLabel.text = @"退回已签发货单";
        } else if(indexPath.row == 2) {
            cell.btLabel.text = @"退回未签";
            cell.fbtLabel.text = @"退回未签发货单";
        }
        return cell;
        
    } else if(indexPath.section == 2){
        if (self.orderContentState == 3) {
            PMJobOrderDetailViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PMJobOrderDetailViewCell" forIndexPath:indexPath];
            
            //车辆信息设置
            NSDictionary *itemData = [self.orderData objectAtIndex:indexPath.row];
            cell.numberLabel.text = [NSString stringWithFormat:@"%u",self.orderData.count - indexPath.row];
            
            NSString *CPH = [itemData objectFormatStringForKey:@"车牌号" defaults:@"未知"];
            NSString *CH = [itemData objectFormatStringForKey:@"车辆编号" defaults:@"无"];
            cell.gcphLabel.text = [NSString stringWithFormat:@"%@(%@)",CPH,CH];
            
            cell.ztLabel.text = [itemData objectFormatStringForKey:@"车辆状态" defaults:@"暂无状态"];
            cell.gcsjLabel.text = [itemData objectFormatStringForKey:@"司机" defaults:@"未收录"];
            cell.ccsjLabel.text = [itemData objectFormatStringForKey:@"出厂时间" defaults:@"未知"];
            cell.hcsjLabel.text = [itemData objectFormatStringForKey:@"回厂时间" defaults:@"未知"];
            //cell.ylLabel.text = [itemData objectFormatStringForKey:@"发货方量" format:@"运量%@方" defaults:@"未知"];
            cell.ylLabel.text = [itemData objectFormatFloatStringForKey:@"发货方量" retain:1 format:@"运量%@方"];
            return cell;
            
        } else {
            UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ActivityIndicat"];
            cell.contentView.frame = CGRectMake(0, 0, cell.contentView.frame.size.width, 55);
            
            if(self.orderContentState == 0) {//加载进度条
                UIActivityIndicatorView *act=[[UIActivityIndicatorView  alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                act.center = CGPointMake(cell.frame.size.width/2, 43.0f);
                act.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
                act.hidesWhenStopped = YES;
                [act startAnimating];
                [cell.contentView addSubview:act];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            } else if(self.orderContentState == 1){//显示无数据提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.text = @"没有车辆信息";
                label.font = [UIFont fontWithName:@"Arial" size:16];
                label.textColor = [UIColor lightGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            } else if(self.orderContentState == 2){//显示失败提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.text = @"加载订单信息失败，点击重试";
                label.font = [UIFont fontWithName:@"Arial" size:16];
                label.textColor = [UIColor lightGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
            }
            return cell;
        }
    }
    
    return nil;
}

#pragma mark - 图表分析

- (void)todaysTaskingDrawCell:(GEObjectValueTableViewCell*)cell indexPath:(NSIndexPath *)indexPath
{
    //绘制标题
    UILabel *titleLable = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, SuperWidth - 40, 22)];
    titleLable.text = @"任务单方量统计（立方）";
    titleLable.font = [UIFont systemFontOfSize:16];
    titleLable.textAlignment = NSTextAlignmentCenter;
    titleLable.textColor = [UIColor colorWithWhite:0 alpha:0.7];
    [cell.contentView addSubview:titleLable];
    
    //绘制标题
    UIButton *subLable = [[UIButton alloc] initWithFrame:CGRectMake(20, 30, SuperWidth - 40, 22)];
    subLable.titleLabel.textColor = [UIColor darkGrayColor];
    [subLable setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    subLable.titleLabel.font = [UIFont systemFontOfSize:13];
    subLable.titleLabel.textAlignment = NSTextAlignmentCenter;
    subLable.userInteractionEnabled = NO;
    [cell.contentView addSubview:subLable];
    
    NSString *showString = [NSString stringWithFormat:@"以下为当日发货数据"];
    NSMutableAttributedString *lableText = [[NSMutableAttributedString alloc] initWithString:showString];
    //    [lableText addAttributes:@{NSUnderlineStyleAttributeName:[NSNumber numberWithInt:NSUnderlineStyleSingle],
    //                               NSForegroundColorAttributeName: [UIColor colorWithRed:51/255.f green:181/255.f blue:229/255.f alpha:1.f] } range:NSMakeRange(lableText.length - 2, 2)];
    [subLable setAttributedTitle:lableText forState:UIControlStateNormal];
    
    PieChartView *_chartView = [[PieChartView alloc] initWithFrame:CGRectMake(5, 33, SuperWidth - 10, 260)];
    _chartView.usePercentValuesEnabled = YES;
    //_chartView.holeTransparent = YES;
    _chartView.holeRadiusPercent = 0.42;
    _chartView.transparentCircleRadiusPercent = 0.45;
//    _chartView.descriptionText = @"";
    [_chartView setExtraOffsetsWithLeft:5.f top:10.f right:5.f bottom:5.f];
    _chartView.userInteractionEnabled = NO;
    _chartView.drawCenterTextEnabled = YES;
    
    _chartView.drawHoleEnabled = YES;
    _chartView.rotationAngle = 0.0;
    _chartView.rotationEnabled = YES;
    _chartView.highlightPerTapEnabled = YES;
    _chartView.drawMarkers = NO;
    _chartView.drawEntryLabelsEnabled = NO;
    
    ChartLegend *l = _chartView.legend;
    l.horizontalAlignment = ChartLegendHorizontalAlignmentRight;
    l.verticalAlignment = ChartLegendVerticalAlignmentCenter;
    l.orientation = ChartLegendOrientationVertical;
    l.xEntrySpace = 7.0;
    l.yEntrySpace = 0.0;
    l.yOffset = 0.0;
    
    [self setPieChartView:_chartView];
    [cell.contentView addSubview:_chartView];
    [_chartView animateWithXAxisDuration:1.4 yAxisDuration:1.4 easingOption:ChartEasingOptionEaseOutBack];
    
}

- (void)setPieChartView:(PieChartView *)chartView
{
    NSDictionary *mDictionary = self.contractBaseInfo;
    
    CGFloat jhfl = [mDictionary objectFormatFloatForKey:@"计划方量" retain:1 except:1];
    CGFloat yfhfl = [mDictionary objectFormatFloatForKey:@"追加方量" retain:1 except:1];
    CGFloat yfh = [mDictionary objectFormatFloatForKey:@"累计发货方量" retain:1 except:1];
    CGFloat wfh = jhfl + yfhfl - yfh;
    CGFloat thyq = [mDictionary objectFormatFloatForKey:@"退回已签方量" retain:1 except:1];
    CGFloat thwq = [mDictionary objectFormatFloatForKey:@"退回未签方量" retain:1 except:1];
    
    NSString *centerTexts = [NSString stringWithFormat:@"计划量\n%0.2fm³\n%0.2fm³\n追加量",jhfl,yfhfl];
    wfh = wfh <= 0 ? 0.0001 : wfh;
    
    NSMutableArray *xVals = [[NSMutableArray alloc] init];
    [xVals addObject:[NSString stringWithFormat:@"已发货量 %0.1f方",yfh]];
    [xVals addObject:[NSString stringWithFormat:@"未发货量 %0.1f方",wfh]];
    [xVals addObject:[NSString stringWithFormat:@"退回已签 %0.1f方",thyq]];
    [xVals addObject:[NSString stringWithFormat:@"退回未签 %0.1f方",thwq]];
    
    NSMutableArray *yVals1 = [[NSMutableArray alloc] init];
    [yVals1 addObject:[[PieChartDataEntry alloc] initWithValue:yfh label:xVals[0]]];
    [yVals1 addObject:[[PieChartDataEntry alloc] initWithValue:wfh label:xVals[1]]];
    [yVals1 addObject:[[PieChartDataEntry alloc] initWithValue:thyq label:xVals[2]]];
    [yVals1 addObject:[[PieChartDataEntry alloc] initWithValue:thwq label:xVals[3]]];
    
    NSMutableArray *colors = [[NSMutableArray alloc] init];
    [colors addObject:ThemeColorGreen];
    [colors addObject:ThemeColorLigthBlue];
    [colors addObject:PNStarYellow];
    [colors addObject:PNRed];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
    paragraphStyle.alignment = NSTextAlignmentCenter;
    
    NSMutableAttributedString *centerText = [[NSMutableAttributedString alloc] initWithString:centerTexts];
    [centerText setAttributes:@{
                                NSFontAttributeName: [UIFont systemFontOfSize:12],
                                NSParagraphStyleAttributeName: paragraphStyle,
                                NSForegroundColorAttributeName:[UIColor darkGrayColor]
                                } range:NSMakeRange(0, 3)];
    [centerText setAttributes:@{
                                NSFontAttributeName: [UIFont systemFontOfSize:12],
                                NSParagraphStyleAttributeName: paragraphStyle,
                                NSForegroundColorAttributeName:[UIColor darkGrayColor]
                                } range:NSMakeRange(centerText.length - 3, 3)];
    [centerText addAttributes:@{
                                NSFontAttributeName: [UIFont systemFontOfSize:12],
                                NSParagraphStyleAttributeName: paragraphStyle,
                                NSForegroundColorAttributeName:ThemeColorLigthBlue
                                } range:NSMakeRange(4, centerText.length - 7)];
    chartView.centerAttributedText = centerText;
    
    PieChartDataSet *dataSet = [[PieChartDataSet alloc] initWithValues:yVals1 label:@"发货类型"];
    dataSet.sliceSpace = 2.0;
    dataSet.colors = colors;
    dataSet.drawValuesEnabled = NO;
    
    PieChartData *data = [[PieChartData alloc] initWithDataSet:dataSet];
    NSNumberFormatter *pFormatter = [[NSNumberFormatter alloc] init];
    pFormatter.numberStyle = NSNumberFormatterPercentStyle;
    pFormatter.maximumFractionDigits = 1;
    pFormatter.multiplier = @1.f;
    pFormatter.percentSymbol = @" %";
    //[data setValueFormatter:pFormatter];
    [data setValueFormatter:[[ChartDefaultValueFormatter alloc] initWithFormatter:pFormatter]];
    [data setValueFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:11.f]];
    [data setValueTextColor:UIColor.whiteColor];
    
    chartView.data = data;
    [chartView highlightValues:nil];
}

#pragma mark
#pragma mark - UITableViewDelegate

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 30)];
    view.backgroundColor = [UIColor whiteColor];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, SuperWidth - 10, 29.5)];
    lable.textColor = [UIColor darkGrayColor];
    lable.font = [UIFont boldSystemFontOfSize:15];
    
    if (section == 0) {
        lable.text = @"任务单明细";
    } else if(section == 1){
        lable.text = @"任务单方量分析";
    } else if(section == 2){
        lable.text = @"车辆信息";
    }
    [view addSubview:lable];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 29.5, SuperWidth, 0.5)];
    lineView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.1];
    [view addSubview:lineView];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] init];
        [cell setDataArray:self.contractData];
        return cell.contentView.frame.size.height;
        
    } else if(indexPath.section == 1){
        if(indexPath.row == 0) return 285;
        else return 48;
        
    } else if(indexPath.section == 2){
        if(self.orderContentState == 3) return 82;
        else return 55;
    }
    
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.section == 1){
        //类型(1:退回已签, 2:退回未签, 3:本日发货方量, 4:本日发车次数, 5:已发车次数)
        NSNumber *typeNumber = [NSNumber numberWithInteger:indexPath.row];
        NSString *jobOrderID = [self.contractBaseInfo objectFormatStringForKey:@"任务单编号"];
        
        PMShipOrderDetailViewController *viewController = [[PMShipOrderDetailViewController alloc] initWithValue:@[typeNumber,jobOrderID]];
        [viewController setStationName:self.stationName StationID:self.stationID];
        [self.navigationController pushViewController:viewController animated:YES];
        
    } else if(indexPath.section == 2){
        if(self.orderContentState == 2) {//加载失败执行
            self.orderContentState = 0;
            [self.tableView reloadData];
            [self getJobOrderInfo];
        }
    }
}

@end

